
qui(
    function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);